import {Action, commit} from '@/store/Utils';
import {store} from '@/store/Store';
import {UserIdentity} from '@/base/model/UserIdentity';
import {deepAssign} from '@/base/util/Objects';
import {getAccoun, getAccount} from '@/base/api/AccountApi';
import {Account} from '@/base/model/Account';
import {getCompany} from '@/base/api/CompanyApi';
import {getResourceMeg} from '@/base/api/ResourceApi';
import {CompanyAccountVo} from '@/base/model/CompanyAccountVo';
import {Resources} from '@/base/Resources';
import {Resource} from '@/base/model/Resource';
import {getAgent} from '@/base/api/AgentApi';
import {Agent} from '@/base/model/Agent';

export class UserState {
  userIdentity = new UserIdentity();
  account = new Account();
  agent = new Agent();
  company = new CompanyAccountVo();
  resources: Array<Resource> = [];
  tepee: string | undefined;
}

abstract class BaseAction implements Action {
  namespace? = 'user';
}

class SetAction extends BaseAction {
  userIdentity?: UserIdentity;
  account?: Account;
  agent?:Agent;
  company?: CompanyAccountVo;
  resources?: Array<Resource> = [];
  tepee?: string;

  static typed(state: UserState, payload: SetAction): void {
    deepAssign(state, payload);
  }
}

export const user = {
  namespaced: true,
  state: new UserState(),
  getters: {},
  actions: {},
  mutations: {
    [SetAction.name]: SetAction.typed
  }
};

export class userBloc {
  static get state(): UserState {
    return store.state.user;
  };

  static reset(): void {
    commit(SetAction, new UserState());
  }

  static renew() { // 点击登录，获取token之后进入
    if (store.state.auth.userType === '1') {
      return getAccoun().then(res => { // 获取account用户个人信息
        commit(SetAction, {userIdentity: res.data});
        store.state.user.tepee = '1';
        return getAccount(res.data.id); // 品牌商
      }).then(res => {
        commit(SetAction, {account: res.data});
        return Promise.all([getCompany(res.data.companyId), getResourceMeg()])
      }).then(res => {
        commit(SetAction, {company: res[0].data, resources: res[1].data});
      });
    } else {
      return getAccoun().then(res => { // 获取agent用户个人信息
        commit(SetAction, {userIdentity: res.data});
        store.state.user.tepee = '2';
        return getAgent(res.data.id); // 品牌商
      }).then(res => {
        commit(SetAction, {agent: res.data});
        return Promise.all([getCompany(res.data.companyId), getResourceMeg()])
      }).then(res => {
        commit(SetAction, {company: res[0].data, resources: res[1].data});
      });
    }
  }

}
